<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 美食社区</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <!-- Cropper.js -->
    <link href="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.12/cropper.min.css" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        .profile-header {
            position: relative;
            height: 300px;
            background-size: cover;
            background-position: center;
            background-color: #f8f9fa;
        }
        .profile-header-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.6));
        }
        .profile-avatar {
            position: absolute;
            bottom: -50px;
            left: 50px;
            width: 150px;
            height: 150px;
            border: 5px solid #fff;
            border-radius: 50%;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
            background-color: #fff;
        }
        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .edit-avatar, .edit-background {
            position: absolute;
            background: rgba(0,0,0,0.5);
            color: #fff;
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .edit-avatar:hover, .edit-background:hover {
            background: rgba(0,0,0,0.7);
        }
        .edit-avatar {
            bottom: 5px;
            right: 5px;
        }
        .edit-background {
            top: 20px;
            right: 20px;
        }
        .profile-content {
            margin-top: 70px;
            padding: 20px;
        }
        .form-label {
            font-weight: 500;
        }
        .cooking-skill-item {
            background-color: #f8f9fa;
            border-radius: 20px;
            padding: 5px 15px;
            margin: 5px;
            display: inline-block;
        }
        .food-preference-item {
            background-color: #fff3e6;
            border-radius: 20px;
            padding: 5px 15px;
            margin: 5px;
            display: inline-block;
            color: #fd7e14;
        }
        .btn-primary {
            background-color: #fd7e14;
            border-color: #fd7e14;
        }
        .btn-primary:hover {
            background-color: #e76b00;
            border-color: #e76b00;
        }
        .cropper-container {
            max-height: 400px !important;
        }
        .food-preference-item, .cooking-skill-item {
            display: inline-block;
            margin: 0.25rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.875rem;
            transition: all 0.3s ease;
        }
        
        .food-preference-item {
            background-color: #fff3e6;
            color: #fd7e14;
            border: 1px solid #ffd7b5;
        }
        
        .cooking-skill-item {
            background-color: #e9ecef;
            color: #495057;
            border: 1px solid #ced4da;
        }
        
        .food-preference-item:hover, .cooking-skill-item:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .food-preference-item .fa-times, .cooking-skill-item .fa-times {
            opacity: 0.5;
            transition: opacity 0.3s ease;
        }
        
        .food-preference-item:hover .fa-times, .cooking-skill-item:hover .fa-times {
            opacity: 1;
        }
        
        .form-select {
            border-radius: 0.5rem;
            border: 1px solid #ced4da;
            padding: 0.75rem 1rem;
            font-size: 0.875rem;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        
        .form-select:focus {
            border-color: #fd7e14;
            box-shadow: 0 0 0 0.25rem rgba(253, 126, 20, 0.25);
        }
        .profile-cover {
            height: 300px;
            background-size: cover;
            background-position: center;
            position: relative;
            background-color: #f8f9fa;
        }
        
        .cover-upload {
            position: absolute;
            bottom: 20px;
            right: 20px;
            background: rgba(0,0,0,0.5);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .cover-upload:hover {
            background: rgba(0,0,0,0.7);
        }
        
        .profile-avatar {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            border: 5px solid #fff;
            margin-top: -75px;
            position: relative;
            background-size: cover;
            background-position: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .upload-avatar {
            position: absolute;
            bottom: 5px;
            right: 5px;
            background: rgba(0,0,0,0.5);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-avatar:hover {
            background: rgba(0,0,0,0.7);
        }
        
        .upload-avatar i {
            color: #fff;
            font-size: 16px;
        }
        
        .profile-info {
            padding: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div th:replace="~{common/header :: header}"></div>

    <div class="container-fluid px-0">
        <!-- 封面图 -->
        <div class="profile-cover" th:style="${user.backgroundImage != null ? 'background-image: url(' + user.backgroundImage + ')' : ''}">
            <label for="coverInput" class="cover-upload">
                <i class="fas fa-camera me-2"></i>更换封面
            </label>
            <input type="file" id="coverInput" accept="image/*" style="display: none;">
        </div>

        <div class="container">
            <!-- 头像 -->
            <div class="d-flex align-items-end">
                <div class="profile-avatar" th:style="'background-image: url(' + ${user.avatar != null ? user.avatar : '/images/default-avatar.jpg'} + ')'">
                    <label for="avatarInput" class="upload-avatar">
                        <i class="fas fa-camera"></i>
                    </label>
                    <input type="file" id="avatarInput" style="display: none" accept="image/*">
                </div>
                <div class="ms-4">
                    <h2 th:text="${user.nickname}">用户昵称</h2>
                    <p class="text-muted" th:text="${user.bio != null ? user.bio : '这个人很懒，什么都没写~'}"></p>
                </div>
            </div>

            <!-- 个人信息 -->
            <div class="profile-info mt-4">
                <form id="profileForm" class="needs-validation" novalidate>
                    <div class="mb-4">
                        <label class="form-label">昵称</label>
                        <input type="text" class="form-control" name="nickname" th:value="${user.nickname}" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">个人简介</label>
                        <textarea class="form-control" name="bio" rows="3" th:text="${user.bio}"></textarea>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">美食偏好</label>
                        <input type="hidden" name="foodPreference" th:value="${user.foodPreference}">
                        <div class="food-preferences-container">
                            <select class="form-select mb-2" id="foodPreferenceSelect">
                                <option value="">选择美食偏好</option>
                                <option value="中餐">中餐</option>
                                <option value="西餐">西餐</option>
                                <option value="日料">日料</option>
                                <option value="韩餐">韩餐</option>
                                <option value="火锅">火锅</option>
                                <option value="烧烤">烧烤</option>
                                <option value="甜点">甜点</option>
                                <option value="面食">面食</option>
                                <option value="海鲜">海鲜</option>
                                <option value="素食">素食</option>
                                <option value="川菜">川菜</option>
                                <option value="粤菜">粤菜</option>
                                <option value="湘菜">湘菜</option>
                                <option value="东南亚菜">东南亚菜</option>
                            </select>
                            <div id="foodPreferencesList" class="mt-2">
                                <th:block th:if="${user.foodPreference != null}">
                                    <span th:each="preference : ${#strings.arraySplit(user.foodPreference, ',')}" 
                                          class="food-preference-item">
                                        <span th:text="${preference}"></span>
                                        <i class="fas fa-times ms-2" style="cursor: pointer;"></i>
                                    </span>
                                </th:block>
                            </div>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">烹饪技能</label>
                        <input type="hidden" name="cookingSkill" th:value="${user.cookingSkill}">
                        <div class="cooking-skills-container">
                            <select class="form-select mb-2" id="cookingSkillSelect">
                                <option value="">选择烹饪技能</option>
                                <option value="炒菜">炒菜</option>
                                <option value="煎炸">煎炸</option>
                                <option value="烘焙">烘焙</option>
                                <option value="煲汤">煲汤</option>
                                <option value="凉菜">凉菜</option>
                                <option value="面点">面点</option>
                                <option value="刀工">刀工</option>
                                <option value="调味">调味</option>
                                <option value="腌制">腌制</option>
                                <option value="蒸煮">蒸煮</option>
                                <option value="烧烤">烧烤</option>
                                <option value="火锅">火锅</option>
                            </select>
                            <div id="cookingSkillsList" class="mt-2">
                                <th:block th:if="${user.cookingSkill != null}">
                                    <span th:each="skill : ${#strings.arraySplit(user.cookingSkill, ',')}" 
                                          class="cooking-skill-item">
                                        <span th:text="${skill}"></span>
                                        <i class="fas fa-times ms-2" style="cursor: pointer;"></i>
                                    </span>
                                </th:block>
                            </div>
                        </div>
                    </div>
                    <div class="d-grid gap-2">
                        <div class="row">
                            <div class="col-6">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-save me-2"></i>保存修改
                                </button>
                            </div>
                            <div class="col-6">
                                <a href="/" class="btn btn-secondary w-100">
                                    <i class="fas fa-home me-2"></i>返回首页
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 头像裁剪模态框 -->
    <div class="modal fade" id="avatarModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更换头像</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <input type="file" class="d-none" id="avatarInput" accept="image/*">
                        <button class="btn btn-outline-primary" onclick="$('#avatarInput').click()">
                            <i class="fas fa-upload me-2"></i>选择图片
                        </button>
                    </div>
                    <div class="img-container">
                        <img id="avatarImage" src="" class="img-fluid">
                    </div>
                    <div class="avatar-preview mt-3" style="width: 150px; height: 150px; overflow: hidden; margin: 0 auto; border-radius: 50%;"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="uploadAvatarBtn">
                        <i class="fas fa-save me-2"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 背景图片裁剪模态框 -->
    <div class="modal fade" id="backgroundModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更换背景图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <input type="file" class="d-none" id="backgroundInput" accept="image/*">
                        <button class="btn btn-outline-primary" onclick="$('#backgroundInput').click()">
                            <i class="fas fa-upload me-2"></i>选择图片
                        </button>
                    </div>
                    <div class="img-container">
                        <img id="backgroundImage" src="" class="img-fluid">
                    </div>
                    <div class="background-preview mt-3" style="width: 320px; height: 180px; overflow: hidden; margin: 0 auto;"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="uploadBackgroundBtn">
                        <i class="fas fa-save me-2"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Cropper.js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
    <script>
        $(document).ready(function() {
            let avatarCropper;
            let backgroundCropper;

            // 头像上传和裁剪
            $('#avatarInput').change(function(e) {
                if (this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#avatarImage').attr('src', e.target.result);
                        if (avatarCropper) {
                            avatarCropper.destroy();
                        }
                        avatarCropper = new Cropper($('#avatarImage')[0], {
                            aspectRatio: 1,
                            viewMode: 1,
                            preview: '.avatar-preview'
                        });
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            });

            // 背景图片上传和裁剪
            $('#backgroundInput').change(function(e) {
                if (this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#backgroundImage').attr('src', e.target.result);
                        if (backgroundCropper) {
                            backgroundCropper.destroy();
                        }
                        backgroundCropper = new Cropper($('#backgroundImage')[0], {
                            aspectRatio: 16/9,
                            viewMode: 1,
                            preview: '.background-preview'
                        });
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            });

            // 上传头像
            $('#avatarInput').change(function() {
                const file = this.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    
                    $.ajax({
                        url: '/api/user/upload/avatar',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            if (res.code === 200) {
                                // 更新头像显示
                                $('.profile-avatar').css('background-image', 'url(' + res.data + ')');
                                // 更新导航栏头像
                                $('.nav-link .avatar-img').attr('src', res.data);
                            } else {
                                alert(res.msg || '上传失败');
                            }
                        },
                        error: function() {
                            alert('上传失败，请稍后重试');
                        }
                    });
                }
            });

            // 上传背景图片
            $('#uploadBackgroundBtn').click(function() {
                if (!backgroundCropper) return;
                
                backgroundCropper.getCroppedCanvas().toBlob(function(blob) {
                    const formData = new FormData();
                    formData.append('file', blob, 'background.jpg');
                    
                    $.ajax({
                        url: '/api/user/upload-background',
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            if (res.code === 200) {
                                // 显示成功消息并刷新页面
                                alert('背景图片上传成功！');
                                window.location.reload();
                            } else {
                                alert('上传失败：' + res.message);
                            }
                        },
                        error: function() {
                            alert('上传失败，请稍后重试');
                        }
                    });
                }, 'image/jpeg');
            });

            // 美食偏好选择
            $('#foodPreferenceSelect').change(function() {
                const value = $(this).val();
                if (value) {
                    addFoodPreference(value);
                    $(this).val(''); // 重置选择
                }
            });

            // 烹饪技能选择
            $('#cookingSkillSelect').change(function() {
                const value = $(this).val();
                if (value) {
                    addCookingSkill(value);
                    $(this).val(''); // 重置选择
                }
            });

            // 删除标签
            $(document).on('click', '.food-preference-item .fa-times', function() {
                $(this).parent().remove();
                updateFoodPreferences();
            });

            $(document).on('click', '.cooking-skill-item .fa-times', function() {
                $(this).parent().remove();
                updateCookingSkills();
            });

            // 表单提交
            $('#profileForm').on('submit', function(e) {
                e.preventDefault();
                
                const formData = {
                    nickname: $('input[name="nickname"]').val(),
                    bio: $('textarea[name="bio"]').val(),
                    foodPreference: $('input[name="foodPreference"]').val(),
                    cookingSkill: $('input[name="cookingSkill"]').val()
                };
                
                $.ajax({
                    url: '/api/user/update-profile',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        if (res.code === 200) {
                            alert('保存成功！');
                            // 更新页面显示
                            window.location.reload();
                        } else {
                            alert(res.msg || '保存失败');
                        }
                    },
                    error: function() {
                        alert('保存失败，请稍后重试');
                    }
                });
            });

            // 初始化已有的美食偏好和烹饪技能
            const initPreferences = $('input[name="foodPreference"]').val();
            if (initPreferences) {
                initPreferences.split(',').forEach(function(pref) {
                    addFoodPreference(pref.trim());
                });
            }

            const initSkills = $('input[name="cookingSkill"]').val();
            if (initSkills) {
                initSkills.split(',').forEach(function(skill) {
                    addCookingSkill(skill.trim());
                });
            }

            // 更新美食偏好隐藏输入
            function updateFoodPreferences() {
                const preferences = [];
                $('#foodPreferencesList .food-preference-item span:first-child').each(function() {
                    preferences.push($(this).text().trim());
                });
                $('input[name="foodPreference"]').val(preferences.join(','));
            }

            // 更新烹饪技能隐藏输入
            function updateCookingSkills() {
                const skills = [];
                $('#cookingSkillsList .cooking-skill-item span:first-child').each(function() {
                    skills.push($(this).text().trim());
                });
                $('input[name="cookingSkill"]').val(skills.join(','));
            }

            // 添加美食偏好
            function addFoodPreference(value) {
                // 检查是否已存在
                if ($('#foodPreferencesList').find('span:contains("' + value + '")').length > 0) {
                    return;
                }
                const item = $('<span class="food-preference-item">')
                    .append($('<span>').text(value))
                    .append('<i class="fas fa-times ms-2" style="cursor: pointer;"></i>');
                $('#foodPreferencesList').append(item);
                updateFoodPreferences();
            }

            // 添加烹饪技能
            function addCookingSkill(value) {
                // 检查是否已存在
                if ($('#cookingSkillsList').find('span:contains("' + value + '")').length > 0) {
                    return;
                }
                const item = $('<span class="cooking-skill-item">')
                    .append($('<span>').text(value))
                    .append('<i class="fas fa-times ms-2" style="cursor: pointer;"></i>');
                $('#cookingSkillsList').append(item);
                updateCookingSkills();
            }

            // 上传封面
            $('#coverInput').change(function() {
                const file = this.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    
                    $.ajax({
                        url: '/api/user/upload/cover',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            if (res.code === 200) {
                                // 更新背景图
                                $('.profile-cover').css('background-image', 'url(' + res.data + ')');
                            } else {
                                alert(res.msg || '上传失败');
                            }
                        },
                        error: function() {
                            alert('上传失败，请稍后重试');
                        }
                    });
                }
            });
        });
    </script>
</body>
</html> 